<?php
/**
 * Created by PhpStorm.
 * User: LiuJiaJun
 * Date: 2018/11/27
 * Time: 8:29
 */

namespace app\storage\service\bom;


use api\storage\common\Constant;
use app\storage\common\AppConstant;
use app\storage\common\Template;
use app\storage\model\BomDetailModel;
use app\storage\model\BomModel;
use app\storage\model\ReelsModel;
use app\storage\model\SupplierStorageModel;
use service\file\CommonFile;

class BaseBomService
{
    protected $bomModel;
    protected $bomDetailModel;

    public function __construct()
    {
        $this->bomModel = new BomModel();
        $this->bomDetailModel = new BomDetailModel();
    }

    public function createBom($reels,$storageUuid)
    {
        if (empty($reels)) {
            return ret_template(false, '没有勾选条码');
        }
        set_time_limit(0);
        $where['status'] = 1;
        $where['storage_uuid'] = $storageUuid;
        $where['reel_id'] = array('in', $reels);
        //到站位上查找数据
        $reelsModel = new ReelsModel();
        $result = $reelsModel->field('sub_materiel_id,reel_id,count,seat_code,container_code')
            ->where($where)->select()
            ->toArray();
        $data = [];//相同物料号的进行合并处理
        $returnReels = [];
        foreach ($result as $k=>$item) {
            if (empty($data[$item['sub_materiel_id']])) {
                $data[$item['sub_materiel_id']] = $item;
            } else {
                $data[$item['sub_materiel_id']]['count'] += intval($item['count']);
            }
            $returnReels[] = Template::returnReelsTemplate($item['reel_id'],$item['seat_code'],$item['sub_materiel_id'],$item['count']);
            unset($result[$k]);
        }
        $supplierUuid = SupplierStorageModel::getSupplierUuidByStorageUuid($storageUuid);
        //写bom表
        $bomUuid = create_uuid();
        $orderId = create_unique_id('BOM');
        $bom = Template::bomTemplate($bomUuid,$orderId,'',$storageUuid,$supplierUuid,AppConstant::REEL_BOM,0,0,'条码出库');
        //写bom_detail表
        $bomDetail = [];
        foreach ($data as $key => $value) {
            $bomDetail[] = Template::bomDetailTemplate($bomUuid,$value['sub_materiel_id'],$value['count']);
        }
        $this->bomModel->startTrans();//开启一个即可
        $res1 = $this->bomModel->table('iwh_bom')->insert($bom);
        $res2 = $this->bomDetailModel->table('iwh_bom_detail')->insertAll($bomDetail);
        if ($res1 >= 1 && $res2 >= 1) {
            $this->bomModel->commit();
            $filePath = Constant::RECORD_RETURN_REELS . $orderId . Constant::RECORD_FILE_SUFFIX;
            $file = new CommonFile($storageUuid, $filePath);
            $file->write($returnReels);
            $result = ret_template(true, '生成订单成功');
        } else {
            $this->bomModel->rollback();
            $result = ret_template(false, '生成订单失败');
        }
        return $result;
    }

}